package com.xps.and.yuntong.service;

import android.app.Notification;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;

import com.xps.and.yuntong.Data.net.UserNetWorks;
import com.xps.and.yuntong.R;
import com.xps.and.yuntong.Utils.RequestParams;
import com.xps.and.yuntong.Utils.SPConstants;
import com.jude.utils.JUtils;
import com.neovisionaries.ws.client.WebSocket;
import com.neovisionaries.ws.client.WebSocketAdapter;
import com.neovisionaries.ws.client.WebSocketException;
import com.neovisionaries.ws.client.WebSocketExtension;
import com.neovisionaries.ws.client.WebSocketFactory;
import com.neovisionaries.ws.client.WebSocketFrame;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import rx.Subscriber;

public class RemoteService extends Service {

    private static final String SERVER1 = "ws://60.205.149.135:8585";//线上接
    private static final String SERVER = "ws://123.56.220.170:8585";//线上接
    // private static final String SERVER = "ws://60.205.149.135:8686";//调试接口
    private static final int TIMEOUT = 5000;
    WebSocket webSocket;
    private MyConnection conn;

    @Override
    public void onCreate() {
        super.onCreate();

        if (conn == null)
            conn = new MyConnection();
        new Thread() {
            @Override
            public void run() {
                super.run();
                connectToServer();
            }
        }.start();
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        Notification.Builder builder = new Notification.Builder(this);
        builder.setSmallIcon(R.drawable.aaa2);
        builder.setContentTitle("韵童司机端");
        builder.setContentText("韵童后台服务正在运行...");
        startForeground(250, builder.build());
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (webSocket != null && !webSocket.isOpen()) {
            new Thread() {
                @Override
                public void run() {
                    super.run();
                    try {
                        webSocket = webSocket.recreate().connect();
                        SharedPreferences sp = JUtils.getSharedPreference();
//                        String user_id = sp.getString("user_id", "");
//                        if (TextUtils.isEmpty(user_id)) return;
//                        ableXinOnline();
                    } catch (WebSocketException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        }
        return super.onStartCommand(intent, flags, startId);
    }





    /**
     * 是否可上线
     */

    void connectToServer() {
        try {
            webSocket = new WebSocketFactory()
                    .setConnectionTimeout(TIMEOUT)
                    .createSocket(SERVER)
                    .addListener(new MySocketAdapter())
                    .setPingPayloadGenerator(() -> RequestParams.getNewInstance().setType("pong").getJson().toString().getBytes())
                    .setPingInterval(1000 * 10)
                    .addExtension(WebSocketExtension.PERMESSAGE_DEFLATE).connect();
            SharedPreferences sp = JUtils.getSharedPreference();
//                    String user_id = sp.getString("user_id", "");
            int user_id = sp.getInt("user_id", -1);
            if (TextUtils.isEmpty(user_id+"")) return;

            webSocket.sendText(RequestParams.getNewInstance().setType("auth").setUid(user_id).getJson().toString());
        } catch (WebSocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (webSocket != null)
            webSocket.disconnect();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private class MyConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {

        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            if (webSocket != null)
                webSocket.disconnect();
        }
    }

    private class MySocketAdapter extends WebSocketAdapter {
        public void onTextMessage(WebSocket websocket, String message) {
            Log.e("RemoteService", message+"11111");
            Intent intent = new Intent();
            intent.putExtra("count", message);
//          intent.setAction("com.and.xps.driverside.service.RemoteService");
            intent.setAction("com.xps.and.yuntong.service.RemoteService");
            sendBroadcast(intent);
        }

        @Override
        public void onConnected(WebSocket websocket, Map<String, List<String>> headers) throws Exception {
            super.onConnected(websocket, headers);
            Log.e("RemoteService", "onConnected");
            JUtils.getSharedPreference().edit().putBoolean(SPConstants.WEBSOCKET_STARTED, true).commit();
        }

        @Override
        public void onFrameSent(WebSocket websocket, WebSocketFrame frame) throws Exception {
            super.onFrameSent(websocket, frame);
            Log.e("RemoteService", "onFrameSent" + frame);
        }

        @Override
        public void onDisconnected(WebSocket websocket, WebSocketFrame serverCloseFrame, WebSocketFrame clientCloseFrame, boolean closedByServer) throws Exception {
            super.onDisconnected(websocket, serverCloseFrame, clientCloseFrame, closedByServer);
            Log.e("RemoteService", "onDisconnected");
        }
    }
}
